package zl.io;
import java.io.File;
import java.io.RandomAccessFile;
import java.io.FileNotFoundException;
import java.io.IOException;

public class RandomAccessFileDemo
{
	public static void main(String[] args)
	{
		File f = new File("C:" + File.separator + "Test.txt");
		RandomAccessFile raf = null;
		if(!f.exists())
		{
			try
			{
				raf = new RandomAccessFile(f,"rw");
				raf.writeBytes("zhangsan");
				raf.writeInt(30);
				raf.writeBytes("lisi    ");
				raf.writeInt(31);
				raf.writeBytes("wangwu  ");
				raf.writeInt(29);	
			}
			catch (FileNotFoundException e)
			{
				e.printStackTrace();
			}
			catch(IOException e)
			{
				e.printStackTrace();
			}
			finally
			{
				if(raf != null)
				{
					try
					{
						raf.close();
					}
					catch (IOException e)
					{
						e.printStackTrace();
					}
				}
			}
		}
		else
		{
			try
			{
				raf = new RandomAccessFile(f,"r");
				byte[] b = new byte[8];
				raf.skipBytes(12);   //���12���ֽ�֮���ȡ
				for(int i = 0; i < 8; i++)
				{
					b[i] = raf.readByte();
				}
				int age = raf.readInt();
				System.out.print("����" + new String(b));
				System.out.println("���䣺" + age);
				raf.seek(0);   //�ӵ�0���ֽڿ�ʼ��ȡ
				for(int i = 0; i < 8; i++)
				{
					b[i] = raf.readByte();
				}
				age = raf.readInt();
				System.out.print("����" + new String(b));
				System.out.println("���䣺" + age);
				raf.skipBytes(12);
				for(int i = 0; i < 8; i++)
				{
					b[i] = raf.readByte();
				}
				age = raf.readInt();
				System.out.print("����" + new String(b));
				System.out.println("���䣺" + age);
			}
			catch (FileNotFoundException e)
			{
				e.printStackTrace();
			}
			catch(IOException e)
			{
				e.printStackTrace();
			}
			finally
			{
				if(raf != null)
				{
					try
					{
						raf.close();
					}
					catch (IOException e)
					{
						e.printStackTrace();
					}
				}
			}
		}
	}
}
